package com.idea.cery.springboot1.filter;

/**
 * @Author:cery
 * @Version 1.0
 * @Date:2020/3/23
 */

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Spring MVC提供的org.springframework.web.servlet.handler.HandlerInterceptorAdapter这个拦截器适配器
 * 不仅可实现Filter的所有功能，还可以更精确的控制拦截精度
 */
@Component
public class CorsFilter implements Filter {

    final static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(CorsFilter.class);

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        //测试session（实践 绑定用户）
        //在application-dev.properties 中配置了 回话超时 时间
        String sid = request.getSession().getId();
        System.out.println("sessionid: " + sid);

        String origin = request.getHeader("Origin");//获取请求头的域名
        if (StringUtils.isNotBlank(origin)) {
            response.addHeader("Access-Control-Allow-Origin", origin);
        }
        String headers = request.getHeader("Access-Control-Request-Headers");
        if (StringUtils.isNotBlank(headers)) {
            response.addHeader("Access-Control-Allow-Headers", headers);
        }

        response.setHeader("Access-Control-Allow-Methods", "*");
        response.addHeader("Access-Control-Allow-Credentials", "true");//允许跨域
        response.setHeader("Access-Control-Max-Age", "3600");
        System.out.println("**过滤器使用**");
        chain.doFilter(req, res);
    }

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void destroy() {
    }
}